package com.tieshan.smartwindow.receiver

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.database.Cursor
import com.tieshan.smartwindow.other.ALPermissionManager
import timber.log.Timber


/*
*   @author Atlantis
*   @data 2021/12/8 15:37
*   简介  
*/
@ExperimentalStdlibApi
class DownloadFinishReceiver(
    val path: String,
    val type: String,
    val downloadManager: DownloadManager
) : BroadcastReceiver() {
    var listener: DownloadFailedListener? = null

    override fun onReceive(context: Context, intent: Intent) {
        //下载完成的广播接收者
        val completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
        checkStatus(completeDownloadId, downloadManager, context.packageName);
    }

    //检查下载状态
    private fun checkStatus(
        completeDownloadId: Long,
        downloadManager: DownloadManager,
        packageName: String
    ) {
        val query = DownloadManager.Query()
        //通过下载的id查找
        query.setFilterById(completeDownloadId)
        val cursor: Cursor = downloadManager.query(query)
        if (cursor.moveToFirst()) {
            val status: Int = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
            when (status) {
                DownloadManager.STATUS_SUCCESSFUL -> {
                    ALPermissionManager.installAndStart(packageName, path)
                    Timber.e("下载成功，Id:$completeDownloadId 包名：$packageName，文件路径：${path},下载类型：$type")
                    cursor.close()
                }
                DownloadManager.STATUS_FAILED -> {
                    listener?.failed()
                    cursor.close()
                }
            }
        }
    }


    interface DownloadFailedListener {
        fun failed()
    }
}